<template>
  <div class="borderbox h100p bgfff posre" :style="{paddingTop:navHeight}">
    <div  class="borderbox fix_top bgblue" :style="{height:navHeight,paddingTop:navTop,paddingBottom:'10px'}" >
      <div class="disflex align-cen h100p pl20">
        <div class="fs20 c38  mr20"
             :class="tabType == 1 ? 'active' : 'title'"
             @click="tab_type_tap(1)">私信</div>
        <div class="fs16 c38 posre"
             :class="tabType == 2 ? 'active' : 'title'"
             @click="tab_type_tap(2)">通知
             <span class="float_number top_number_position" v-if="allLength">
               {{allLength}}
             </span>
             </div>
      </div>
    </div>

    <!--msg lists 需要执行分段 添加 当聊天用户超过200后-->
    <template v-if="msgList.imList.length > 0 && tabType == 1">
      <div class="overhidden posab w100p bradiustr10" :class="scrollChange ? '' : 'z-index100'" style="margin-top:-20rpx">
        <div class="bgfff bradiustr10">
          <div v-for="(msgitem,k) in lists" :key="k" class="bbf5f6">
            <MsgBox :msg="msgitem"
                    :isImMsg="true"
                    :istime="msgitem.newestMessage && msgitem.newestMessage.time"
                    @row_tap="row_tap(msgitem.userId||'',msgitem.cardId||'',msgitem.logo||'',msgitem.name||'',msgitem.wxCode||'', msgitem.phone||'')" >
            </MsgBox>
          </div>
        </div>
      </div>
    </template>
    <div v-else-if="tabType == 2" class="overhidden bgfff posab w100p bradiustr10" :class="scrollChange ? '' : 'z-index100'" style="margin-top:-20rpx">
      <div class="pl15 pr15 bbf5f6">
        <div class="disflex jsbet h44 align-cen ">
          <div class="fs14 c78">通知列表</div>
          <div class="disflex align-cen">
            <img :src="icon1" class="w15 h15 mr7" alt="">
            <p class="fs14 cblue" @click="show_dialog_box">全部已读</p>
          </div>
        </div>
      </div>
      <div class="pl15 pr15">
        <!-- 订单通知 -->
        <div class="pl15 pr15 pt20 pb20 bbf5f6" v-if="orderList.length > 0">
          <div class="pl15 pr15 mb20">
            <div class="disflex jsbet align-cen">
              <div class="disflex align-cen posre">
                <img :src="icon2" class="w30 h30 mr11" alt="">
                <div class="fs18 c38 fbold">订单通知</div>
                <span class="float_number list_number_positon" v-if="orderLength">{{orderLength}}</span>
              </div>
              <p class="fs12 ca8">{{orderTime}}</p>
            </div>
          </div>
          <div class="msg_box  pt20 pr23 pb16 pl15 posre">
            <div class="disflex" v-for="(item,index) in orderList" :key="index">
              <div class="w4 h4 bgblue bradius50p mr7 mt13">
              </div>
              <div class="flex1 lh27 fs14 c38" @click="notification_tap(item)">
                <span class="cblue">{{item.message}}</span>
                  {{item.decrit}}
              </div>
            </div>
            <div class="triangle">

            </div>
          </div>
        </div>
        <!-- 表单通知 -->
        <div class="pl15 pr15 pt20 pb20 bbf5f6" v-if="formList.length > 0">
          <div class="pl15 pr15 mb20">
            <div class="disflex jsbet align-cen">
              <div class="disflex align-cen posre">
                <img :src="icon3" class="w30 h30 mr11" alt="">
                <div class="fs18 c38 fbold">表单通知</div>
                <span class="float_number list_number_positon" v-if="formLength">{{formLength}}</span>
              </div>
              <p class="fs12 ca8">{{formTime}}</p>
            </div>
          </div>
          <div class="msg_box  pt20 pr23 pb16 pl15 posre">
            <div class="disflex" v-for="(item,index) in formList" :key="index">
              <div class="w4 h4 bgblue bradius50p mr7 mt13">
              </div>
              <div class="flex1 lh27 fs14 c38" @click="notification_tap(item)">
                <span class="cblue">{{item.message}}</span>用户提交了“客户反馈表单”，快去看看吧
              </div>
            </div>
            <div class="triangle"></div>
          </div>
        </div>
        <!-- 动态通知 -->
        <div class="pl15 pr15 pt20 pb20 bbf5f6" v-if="dynamicList.length > 0">
          <div class="pl15 pr15 mb20">
            <div class="disflex jsbet align-cen">
              <div class="disflex align-cen posre">
                <img :src="icon3" class="w30 h30 mr11" alt="">
                <div class="fs18 c38 fbold">动态通知</div>
                <span class="float_number list_number_positon" v-if="dynamicLength">{{dynamicLength}}</span>
              </div>
              <p class="fs12 ca8">{{dynamicTime}}</p>
            </div>
          </div>
          <div class="msg_box  pt20 pr23 pb16 pl15 posre">
            <div class="disflex" v-for="(item,index) in dynamicList" :key="index">
              <div class="w4 h4 bgblue bradius50p mr7 mt13">
              </div>
              <div>
                <div class="flex1 lh27 fs14 c38" @click="notification_tap(item)">
                  <span class="cblue">{{item.message}}</span>
                  {{item.decrit}}
                </div>
              </div>
            </div>
            <div class="triangle"></div>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="overhidden bgfff posab w100p bradiustr10 zindex999" style="margin-top:-20rpx">
      <NoData>暂无消息</NoData>
    </div>
    <div v-if="showDialog">
      <promptDialogBox
        :dialog_title="dialog_title"
        @dialogbox_tap="dialogbox_tap"
        @btn_tap="btn_tap"
      ></promptDialogBox>
    </div>
  </div>
</template>

<script>
  import store from '../../store/index'
  import MsgBox from '@/components/msgBox' // 订单项
  import websocket from  '../../utils/websocket'
  import NoData from '@/components/noData'
  import AddNoticeNum from '@/components/AddNoticeNum';
  import {authSubscribeMessage,authSubscribeOrder} from '../../utils/auth.js'
  import {mapActions, mapGetters, mapState} from 'vuex';
  import WXAJAX from "../../utils/request";
  import utils from "../../utils/index"
  import promptDialogBox from "@/components/promptDialogBox"

  export default {
    name: '',
    components: {MsgBox, NoData, AddNoticeNum ,promptDialogBox},
    data() {
      return{
        msg_lists:[ ],
        notice:[{
          title:'需求',
          isCheck:false
        },{
          title:'需求',
          isCheck:false
        },{
          title:'产品',
          isCheck:false
        },{
          title:'名片',
          isCheck:false
        }],
        page: 1,
        navHeight:'',
        navBarUserHeight:'',
        navTop:'',
        tabType:1,
        icon1:WXAJAX.imgBackUrl +'/yimai_photos/user/msg/ic_clear@2x.png',
        icon2:WXAJAX.imgBackUrl +'/yimai_photos/user/msg/ic_message_form@2x.png',
        icon3:WXAJAX.imgBackUrl +'/yimai_photos/user/msg/ic_message_order@2x.png',
        icon4:WXAJAX.imgBackUrl +'/yimai_photos/user/msg/ic_message_recently@2x.png',
        scrollChange:false,
        notificationList:'',
        orderList:'', //订单时间
        formList:'', //表单时间
        dynamicList:'', //动态时间
        orderLength:0, //订单数量
        formLength:0, //表单数量
        dynamicLength:0, //动态数量
        orderTime:'', //订单时间
        formTime:'', //表单时间
        dynamicTime:'', //动态时间
        allLength:'',
        showDialog:false,
        dialog_title:''
      }
    },
    async onPullDownRefresh() {
      if(this.tabType == 2){
        return
      }
      //console.log(this.tabType)
      websocket.sendSocketJSON("108",this.page);
      setTimeout(()=>{
        wx.stopPullDownRefresh();
      }, 2*1000)
    },
    onReachBottom(){
      if(this.tabType == 2){
        return
      }
      this.page++;
      websocket.sendSocketJSON("108",this.page);
    },
    /** tab点击 */
    onTabItemTap(item) {
     //订阅授权 信息相关
     authSubscribeMessage(this.subscriptionNew);
    },
    onLoad(){
      this.calculateNavBarHeight()
    },
    onShow(){
      this.page = 1;
      websocket.sendSocketJSON("108",this.page);
      if (!wx.getStorageSync('token')) {
        wx.setStorageSync('redirectPage','/pages/msg/main');
        wx.reLaunch({url:'/pages/wxLogin/main'});
        return;
      }
      this.$refs.noticeNum && this.$refs.noticeNum.getTotalNum();
      websocket.sendSocketJSON('1011')

    },
    onHide(){
      this.showDialog = false
    },
    watch:{
      'msgCont.notificationList': {
        deep: true,
        immediate: true,
        handler(value) {
          console.log('22222', value)
          this.notificationList = value.data
          if(!this.notificationList){
            return
          }
          this.orderFilter()
          this.formFilter()
          this.dynamicFilter()
        }
      },
      // notificationList(newVal,old){
      //   console.log(newVal)
      //   if(!newVal){
      //     return
      //   }

      // },
    },
    onPageScroll (e) {
      if(e.scrollTop > 10){
        this.scrollChange = true
      }else{
        this.scrollChange = false
      }
    },
    computed:{
      msgList() {
        console.debug("store接收的消息+++", store.state.msgList.msglist);
        return store.state.msgList.msglist;
      },
      lists(){
        let lists = JSON.parse(JSON.stringify(this.msgList.imList || []));
        //分页取聊天记录
        return lists.splice(0, 10 * this.page)
      },
      ...mapState(['msgCont']),
      ...mapGetters(["currentCompany","subscriptionNew"])
    },
    methods: {
      calculateNavBarHeight() {
        if (getApp().globalData.menuButtonBounding === 0) {
          getApp().globalData.menuButtonBounding = wx.getMenuButtonBoundingClientRect();
        }
        let menuButtonBounding = getApp().globalData.menuButtonBounding;
        wx.getSystemInfo({
          success: res => {
            let statusBarHeight = res.statusBarHeight; //胶囊按钮与顶部的距离
            let navHeight =
              statusBarHeight +
              (menuButtonBounding.top - statusBarHeight) * 2 +
              menuButtonBounding.height; //导航高度
            let navBarUserHeight = navHeight - statusBarHeight;

            this.navHeight = navHeight + 10 + "px";
            this.navTop = statusBarHeight + "px";
            wx.setStorageSync('navTop',this.navTop)
            this.navBarUserHeight = navBarUserHeight + "px";
          },
          fail(err) {
            //console.log(err);
          }
        });
      },
      row_tap(id,cardid,logo,name, wxCode, phone){
        wx.navigateTo({url: '../IM/main?userId='+id+'&logo='+logo+'&type=2&cardId='+cardid+'&name='+name+'&wxCode='+wxCode +'&phone='+phone})
      },
      tab_type_tap(type){
        this.tabType = type
        this.scrollChange = false
        this.showDialog = false
      },
      //分割消息内容
      //noticeType为消息类型  4：订单消息 、5：表单消息、6：动态消息
      orderFilter(){
        let orderLists = []
        let unreadLength = ''
        let arr = this.notificationList
        //判断是否已读
        for(var i in arr){
          if(arr[i].noticeType == 4 || arr[i].noticeType == 7){
            orderLists.push(arr[i])
            if(arr[i].noticeType == 4){
              switch(arr[i].status){
                case 1 :
                  arr[i].toPages = '../orderLists/main';
                  arr[i].decrit = "商品已被下单，快去看看吧";
    ;                break;
                case 2 :
                  arr[i].toPages = '../orderLists/main';
                  arr[i].decrit = "商品已准备发货，快去看看吧";
                  break;
                case 3 :
                  arr[i].toPages = '../orderLists/main';
                  arr[i].decrit = "商品已准备收货，快去看看吧";
                  break;
                case 4 :
                  arr[i].toPages = '../orderLists/main';
                  arr[i].decrit = "商品订单已完成，快去看看吧";
                  break;
                case 5 :
                  arr[i].toPages = '../orderLists/main';
                  arr[i].decrit = "商品交易已取消，快去看看吧";
                  break;
                case 6 :
                  arr[i].toPages = '../orderLists/main';
                  arr[i].decrit = "商品已退款成功，快去看看吧";
                  break;
                default:
                  break;
              }
            }else if(arr[i].noticeType == 7){
              arr[i].toPages = '../companyPack/appointmentManage/main';
              arr[i].decrit = "商品预约成功，快去看看吧";
            }
          }
        }
        orderLists = orderLists.reverse()
        unreadLength = orderLists.filter( v=>{
          return v.type == 0
        })
        if(orderLists.length > 0){
          this.orderTime = utils.getdate(orderLists[0].time,'monthTime')
        }
        this.orderLength = unreadLength.length
        this.orderList = orderLists.slice(0,3)
      },
      formFilter(){
        let unreadLength = ''
        let orderList = []
        let arr = this.notificationList
        for(var i in arr){
          if(arr[i].noticeType == 5){
            arr[i].toPages = '../webSiteControl/userList/main';
            orderList.push(arr[i])
          }
        }
        orderList = orderList.reverse()
        unreadLength = orderList.filter( v=>{
          return v.type == 0
        })
        console.log(orderList)
        if(orderList.length > 0){
          this.formTime = utils.getdate(orderList[0].time,'monthTime')
        }
        this.formLength = unreadLength.length
        this.formList = orderList.slice(0,3)
      },
      dynamicFilter(){
        let unreadLength = ''
        let orderList = []
        let arr = this.notificationList
        for(var i in arr){
          if(arr[i].noticeType == 6){
            switch(arr[i].status){
              case 1 :
                arr[i].toPages = '../companyPack/dynamicControl/main';
                arr[i].decrit = "用户分享了您的动态，快去看看吧";
;                break;
              case 2 :
                arr[i].toPages = '../companyPack/dynamicControl/main';
                arr[i].decrit = "用户评论了您的动态，快去看看吧";
                break;
              case 3 :
                arr[i].toPages = '../companyPack/dynamicControl/main';
                arr[i].decrit = "用户点赞了您的动态，快去看看吧";
                break;
              case 4 :
                arr[i].toPages = '../companyPack/shareRecord/main';
                arr[i].decrit = "用户分享了您的文章，快去看看吧";
                break;
              case 5 :
                arr[i].toPages = '../companyPack/shareRecord/main';
                arr[i].decrit = "用户评论了您的文章，快去看看吧";
                break;
              case 6 :
                arr[i].toPages = '../companyPack/shareRecord/main';
                arr[i].decrit = "用户点赞了您的文章，快去看看吧";
                break;
              default:
                break;
            }
            if(arr[i].status)
            orderList.push(arr[i])
          }
        }
        orderList = orderList.reverse()
        unreadLength = orderList.filter( v=>{
          return v.type == 0
        })
        this.dynamicLength = unreadLength.length
        if(orderList.length > 0){
          this.dynamicTime = utils.getdate(orderList[0].time,'monthTime')
        }
        //消息总数
        this.allLength = this.orderLength+ this.formLength +this.dynamicLength
        if(this.allLength){
          this.dialog_title = '此操作会将未读的通知提示全部标记为已读'
        }else{
          this.dialog_title = ''
        }
        this.dynamicList = orderList.slice(0,3)
      },
      notification_tap(item){
        let param = {
          code:1012,
          targetId:item.companyId,
          noticeType:item.noticeType
        }
        websocket.updateStatus(param)
        wx.navigateTo({
          url:item.toPages
        })
      },
      show_dialog_box(){
        this.showDialog = true
      },
      //设置消息读取弹框显隐
      dialogbox_tap(){
        this.showDialog = false
      },
      //设置消息全部已读
      btn_tap(){
        websocket.sendSocketJSON('1012')
        wx.showLoading({
          title:'清理中...',
          mask:true
        })
        setTimeout(function(){
          websocket.sendSocketJSON('1011')
          wx.hideLoading()
        },2000)

        this.showDialog = false
      }
    }
  }
</script>
<style>
page{
  background: #ffffff;
}
</style>
<style scoped>
.title{
  font-size: 36upx;
  color: #ffffff;
  opacity: 0.4;
  transition: all .2s;
}
.active{
  font-size: 40upx;
  color: #ffffff;
  transition: all .2s;
  font-weight: bold;
}
.msg_box{
  background: #F5F5F6;
  border-radius: 10upx;
}
.triangle{
  position: absolute;
  left: 30upx;
  top: -30upx;
  width: 0;
  height: 0;
  border-width: 0 30upx 30upx;
  border-style:solid;
  border-color: transparent transparent #F5F5F6;
}
.float_number{
  position: absolute;
  display: block;
  width: 30upx;
  height: 30upx;
  background: #FD634E;
  border-radius: 50%;
  font-size: 18upx;
  color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;

}
.list_number_positon{
  top: -15upx;
  left: 40upx;
}
.top_number_position{
  top: -5upx;
  left: 65upx;
}
.z-index100{
  transition: all 0.4s;
  z-index: 100;
}
</style>
